﻿

using MotionRobot.Models;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Newtonsoft.Json;
using System.IO;
using LeaderCCSLaserUI.Common;
using System.Collections.Concurrent;

namespace LeaderCCSLaserUI.Services
{
    public class GTSCardService : IGTSCardService
    {
        short SRtn;
        short AxisCount;
        public AxisParm A1 { get; set; }//X轴
        public AxisParm A2 { get; set; }//Y轴
        public AxisParm A3 { get; set; }
        public AxisParm A4 { get; set; }
        public AxisParm A5 { get; set; }
        public AxisParm A6 { get; set; }
        public AxisParm A7 { get; set; }
        public AxisParm A8 { get; set; }
        public bool Connected { get; set; }
        public ConcurrentBag<FlyImage> ImageList { get; set; } = new ConcurrentBag<FlyImage>();
        public bool Init(int axisCount, string axisParmFileName, string cfgFileName)
        {
            Connected = false;
            try
            {
                List<AxisParm> axisParmList;
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, $"{axisParmFileName}.json"));
                axisParmList = JsonConvert.DeserializeObject<List<AxisParm>>(jsonString);
                A1 = axisParmList[0];
                A2 = axisParmList[1];
                A3 = axisParmList[2];
                A4 = axisParmList[3];
                A5 = axisParmList[4];
                A6 = axisParmList[5];
                A7 = axisParmList[6];
                A8 = axisParmList[7];
                AxisCount = (short)axisCount;
                SRtn = gts.mc.GT_Open(A1.CardNo, 0, 1);
                if (SRtn != 0)
                {
                    return false;
                }
                SRtn = gts.mc.GT_Reset(A1.CardNo);
                if (SRtn != 0)
                {
                    return false;
                }
                SRtn = gts.mc.GT_LoadConfig(A1.CardNo, $"{cfgFileName}.cfg");
                if (SRtn != 0)
                {
                    return false;
                }
                SRtn = gts.mc.GT_ClrSts(A1.CardNo, A1.AxisId, (short)axisCount);
                if (SRtn != 0)
                {
                    return false;
                }
                Connected = true;
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;
            }
        }
    }
}
